// OCR处理模块 - 负责图片文字识别
import { addRecord } from './data.js';
import { escapeHtml } from './utils.js';

// 动态加载 Tesseract.js
async function loadTesseract() {
  // 检查主世界的Tesseract对象
  const mainWorldTesseract = typeof window.wrappedJSObject !== 'undefined' ? 
    window.wrappedJSObject.Tesseract : 
    (window.Tesseract || undefined);
    
  if (mainWorldTesseract) return mainWorldTesseract;
  
  const script = document.createElement('script');
  // ✅ 兼容性处理：确保 chrome 对象可用
  if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL) {
    script.src = chrome.runtime.getURL('lib/tesseract.min.js');
  } else {
    script.src = new URL('../lib/tesseract.min.js', import.meta.url).href;
  }
  
  document.head.appendChild(script);

  return new Promise((resolve, reject) => {
    script.onload = () => {
      // 等待Tesseract.js完全初始化
      let attempts = 0;
      const maxAttempts = 50; // 最多等待5秒
      const checkTesseract = () => {
        // 检查隔离世界和主世界的Tesseract对象
        const tesseract = typeof window.wrappedJSObject !== 'undefined' ? 
          window.wrappedJSObject.Tesseract : 
          window.Tesseract;
          
        if (tesseract) {
          resolve(tesseract);
        } else if (attempts < maxAttempts) {
          attempts++;
          setTimeout(checkTesseract, 100);
        } else {
          reject(new Error('Tesseract.js 初始化超时'));
        }
      };
      checkTesseract();
    };
    script.onerror = () => {
      reject(new Error('Tesseract.js 加载失败'));
    };
  });
}

async function getLocalResourceUrl(path) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(
      {
        type: 'GET_RESOURCE_URL',
        path: path,
      },
      (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response.url);
        }
      }
    );
  });
}

async function getTesseractUrls() {
  return new Promise((resolve, reject) => {
    const handler = (event) => {
      if (event.data.type === 'TESSERACT_URLS_RESPONSE') {
        resolve(event.data.data);
        window.removeEventListener('message', handler);
      }
      if (event.data.type === 'TESSERACT_URLS_ERROR') {
        reject(new Error(event.data.error));
        window.removeEventListener('message', handler);
      }
    };
    window.addEventListener('message', handler);

    // 发送请求
    window.postMessage({ type: 'GET_TESSERACT_URLS' }, '*');
  });
}

// 更新上传区域显示文件名
function showFileName(fileName) {
  const uploadArea = document.querySelector('.upload-area');
  if (uploadArea) {
    const fileNameElement = uploadArea.querySelector('.file-name');
    if (fileNameElement) {
      fileNameElement.textContent = escapeHtml(fileName);
      fileNameElement.style.visibility = 'visible';
    }
    
    // 隐藏提示文字
    const hintTextElement = uploadArea.querySelector('.hint-text');
    if (hintTextElement) {
      hintTextElement.style.visibility = 'hidden';
    }
  }
}

// 隐藏文件名并显示提示文字
function hideFileName() {
  const uploadArea = document.querySelector('.upload-area');
  if (uploadArea) {
    const fileNameElement = uploadArea.querySelector('.file-name');
    if (fileNameElement) {
      fileNameElement.textContent = '';
      fileNameElement.style.visibility = 'hidden';
    }
    
    // 显示提示文字
    const hintTextElement = uploadArea.querySelector('.hint-text');
    if (hintTextElement) {
      hintTextElement.style.visibility = 'visible';
    }
  }
}

export async function handleImage(file, records, saveRecords, addRecordToUI) {
  if (!file) return;

  // 显示文件名
  showFileName(file.name);

  const reader = new FileReader();
  reader.onload = async (e) => {
    const imgDataUrl = e.target.result;
    // 传递文件名到extractText函数
    await extractText(imgDataUrl, addRecordToUI, file.name || '未命名图片');
  };
  reader.readAsDataURL(file);
}

// 使用 Tesseract.js 提取文字（直接调用recognize方法，不使用worker模式）
export async function extractText(imgDataUrl, addRecordToUI, fileName) {
  const uploadArea = document.querySelector('.upload-area');

  if (uploadArea) {
    // 在识别过程中更新提示文字
    const hintTextElement = uploadArea.querySelector('.hint-text');
    if (hintTextElement) {
      hintTextElement.textContent = '识别中...';
      hintTextElement.style.visibility = 'visible';
    }
    
    // 保持文件名显示
    const fileNameElement = uploadArea.querySelector('.file-name');
    if (fileNameElement) {
      fileNameElement.style.visibility = 'visible';
    }
    
    // 禁用上传区域的交互功能
    uploadArea.style.pointerEvents = 'none';
    uploadArea.style.opacity = '0.7';
    // 添加processing类以改善视觉反馈
    uploadArea.classList.add('processing');
  }

  try {
    const Tesseract = await loadTesseract();
    
    // 检查Tesseract是否正确加载
    if (!Tesseract || typeof Tesseract.recognize !== 'function') {
      throw new Error('Tesseract.js 加载不完整或recognize方法不存在');
    }
    
    console.log('Tesseract版本信息:', Tesseract);

    console.log('开始调用Tesseract.createWorker()');
    const { workerPath, corePath, langPath } = await getTesseractUrls();
    const worker = await Tesseract.createWorker('chi_sim+eng', 1, {
        workerPath: workerPath,
        corePath: corePath,
        langPath: langPath,
        logger: info => {
            console.log('OCR进度:', info);
        }
    });
    let result;
    try {
        result = await worker.recognize(imgDataUrl);
    } catch (error) {
        console.error('开始调用Tesseract.createWorker()，失败：', error);
        alert('识别失败，请重试');
    } finally {
        worker.terminate();
    }
    console.log('worker.recognize() 执行成功');
    
    let text = result.data.text.trim();

    if (text) {
        // 处理文字
        // 临时替换换行符
        text = text.replace(/\n/g, '{{NEWLINE}}');
        
        // 保留英文单词间的空格
        // 先移除所有空格
        text = text.replace(/ /g, '');
        // 然后在英文单词之间添加空格（简单实现）
        text = text.replace(/([a-zA-Z])([中文\u4e00-\u9fff])/gi, '$1 $2');
        text = text.replace(/([中文\u4e00-\u9fff])([a-zA-Z])/gi, '$1 $2');
        
        // 移除多余空格（保留单个空格）
        text = text.replace(/ +/g, ' ');
        
        // 移除标点符号前后的空格
        const punctuation = /[。，、；：！？（）「」【】《》""''.,;:!?()[]{}]/g;
        text = text.replace(/\s*([，。！？；：""''（）【】])\s*/g, '$1');
        
        // 恢复换行符
        text = text.replace(/{{NEWLINE}}/g, '\n');
      const record = {
        id: Date.now(),
        text,
        time: new Date().toLocaleString(),
        fileName: fileName || '未命名图片', // 添加文件名
        source: 'by tesseract.js' // 添加来源信息
      };
      
      addRecord(record);
      addRecordToUI(record);
    } else {
      alert('未提取到文字');
    }
  } catch (err) {
    console.error('OCR 失败:', err);
    alert('识别失败，请重试');
  } finally {
    if (uploadArea) {
      // 识别完成后隐藏文件名并恢复提示文字
      hideFileName();
      
      // 恢复提示文字内容
      const hintTextElement = uploadArea.querySelector('.hint-text');
      if (hintTextElement) {
        hintTextElement.textContent = '点击上传、拖拽图片或粘贴截图';
      }
      
      // 恢复上传区域的交互功能
      uploadArea.style.pointerEvents = 'auto';
      uploadArea.style.opacity = '1';
      // 移除processing类
      uploadArea.classList.remove('processing');
    }
  }
}